<template>
    <div class="tinymce-box">
        <editor :key="tinymceFlag" v-model="tinymce_value" :init="init"></editor>
    </div>
</template>
<script>
import store from '../store/store'
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/models/dom'
import 'tinymce/themes/silver'
import 'tinymce/icons/default'
// 引入你需要的插件
import 'tinymce/plugins/code';
import 'tinymce/plugins/link';
import 'tinymce/plugins/table';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/advlist';
import 'tinymce/plugins/image';
import 'tinymce/plugins/media';
// 自己处理上传图片
const image_upload = (blobInfo, progress) => new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.withCredentials = false;
    xhr.open('POST', '/common/upload/file');
    xhr.setRequestHeader("Authorization", store.getters.token);
    xhr.upload.onprogress = (e) => {
        progress(e.loaded / e.total * 100);
    };
    xhr.onload = function () {
        var json;
        if (xhr.status != 200) {
            reject('HTTP Error: ' + xhr.status);
            return;
        }
        json = JSON.parse(xhr.responseText);
        if (!json || json.code != 200) {
            reject('上传失败: ' + json.message);
            return;
        }
        // 成功了的处理
        resolve(json.result.url);
    };
    xhr.onerror = () => {
        reject('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
    };
    const formData = new FormData();
    // formData.append('fireflyFile', file, file.name );//此处与源文档不一样
    formData.append('imgFile', blobInfo.blob(), blobInfo.filename());
    formData.append('dir', 'images');
    xhr.send(formData);
});

export default {
    name: 'TinymceEditor',
    data() {
        return {
            tinymce_value: this.tinymceValue,
            init: {
                language_url: '/statics/tinymce/langs/zh_CN.js',// 语言包的路径
                language: 'zh_CN',//语言
                skin_url: '/statics/tinymce/skins/ui/oxide',// skin路径
                content_css: '/statics/tinymce/skins/content/default/content.css',
                height: 300,//编辑器高度
                branding: true,//是否禁用“Powered by TinyMCE”
                menubar: false,//顶部菜单栏显示,
                convert_urls: false, // 不处理内容里边的所有URL
                toolbar: true, //隐藏菜单栏
                height: 500,
                convert_fonts_to_spans: false,// 转换字体元素为SPAN标签，默认为true
                valid_elements: '*[*]', // 所有元素有效
                valid_children: '*[*]', // 所有子元素有效
                toolbar: 'code bold italic underline strikethrough forecolor backcolor formatselect fontselect fontsizeselect cut copy paste link image media table bullist numlist  alignleft aligncenter alignright alignjustify outdent indent blockquote subscript superscript removeformat undo redo',
                plugins: ['code', 'link', 'table', 'advlist', 'lists', 'image', 'media'], //选择需加载的插件
                //想要哪一个图标提供本地文件选择功能，参数可为media(媒体)、image(图片)、file(文件)
                file_picker_types: 'image file media',
                // 自己处理上传图片
                images_upload_handler: image_upload,
                // 文件上传
                file_picker_callback: function (callback, value, meta) {
                    //要先模拟出一个input用于上传本地文件
                    var input = document.createElement('input');
                    input.setAttribute('type', 'file');
                    //你可以给input加accept属性来限制上传的文件类型
                    input.setAttribute('accept', '.jpg,.png,.gif,.jpeg,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt,.md,.rar,.zip');
                    input.click();
                    input.onchange = function () {
                        var file = this.files[0];
                        var xhr, formData;
                        console.log(file.name);
                        xhr = new XMLHttpRequest();
                        xhr.withCredentials = false;
                        xhr.open('POST', '/common/upload/file');
                        xhr.setRequestHeader("Authorization", store.getters.token);
                        xhr.onload = function () {
                            var json;
                            if (xhr.status != 200) {
                                failure('HTTP Error: ' + xhr.status);
                                return;
                            }
                            json = JSON.parse(xhr.responseText);
                            if (!json || json.code != 200) {
                                failure('上传失败: ' + json.message);
                                return;
                            }
                            // 成功了的处理
                            callback(json.result.url);
                        };
                        formData = new FormData();
                        formData.append('dir', 'files');
                        formData.append('imgFile', file, file.name);
                        xhr.send(formData);
                    }
                },
            },
            tinymceFlag: 1,
        }
    },
    components: {
        Editor
    },
    props: {
        tinymceValue: {
            type: String,
            default: ''
        }
    },
    // 监听父组件传值的变化
    watch: {
        tinymceValue(curVal) {
            // console.log('watch')
            this.tinymce_value = curVal;
        }
    },
    mounted() {
        // tinymce.init({});
        this.tinymceFlag++
        // console.log('this.tinymceValue -' + this.tinymceValue)
        this.tinymce_value = this.tinymceValue
    },
    methods: {},
    beforeDestroy() {
        tinymce.remove();
    },
}
</script>